using AutoMapper;
using B.S.Data.MES.API.Applications.BaseData.Command.BOMCommand;
using B.S.Domain.BasicData.MaterialManagement.BOM;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;

namespace B.S.Data.MES.API.Applications.BaseData.CommandHandlers.BOMCommandHandlers
{
    public class UpdateBOMCommandHandler : IRequestHandler<UpdateBOMCommand, APIRequst<int>>
    {
        private readonly IBaseRepository<BOM> _bomRepository;
        private readonly IMapper _mapper;

        public UpdateBOMCommandHandler(IBaseRepository<BOM> bomRepository, IMapper mapper)
        {
            _bomRepository = bomRepository;
            _mapper = mapper;
        }

        public async Task<APIRequst<int>> Handle(UpdateBOMCommand request, CancellationToken cancellationToken)
        {
            APIRequst<int> result = new APIRequst<int>();
            var sideme = _bomRepository.GetAll().Where(x => x.BomId == request.BomId).FirstOrDefault();
            if(sideme==null)
            {
                result.Code = RequstCode.失败;
                result.Msg = RequstCode.失败.ToString()+"BOM不存在";
                return await Task.FromResult(result);
            }
            var codeExists = _bomRepository.GetAll().Where(x => x.Materialcode == request.Materialcode && x.BomId == request.BomId && !x.isDel).FirstOrDefault();
            if(codeExists!=null)
            {
                result.Code = RequstCode.失败;
                result.Msg = RequstCode.失败.ToString() + "该BOM编码已存在，请重新输入";
                return await Task.FromResult(result);
            }
           sideme.Materialcode = request.Materialcode;
            sideme.Bname= request.Bname;
            sideme.version = request.version;
            sideme.UseNum = request.UseNum;
            sideme.describe=request.describe;
            sideme.UpdateName = request.UpdateName;
            sideme.UpdateTime = DateTime.Now;
            
           
            
            await _bomRepository.Update(sideme);
            
            return new APIRequst<int>
            {
                Code = RequstCode.成功,
                Msg = RequstCode.成功.ToString()
            };
        }
    }
}